// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/questionnaire/api/IbQuestionnaireApi'

import OneClass from '@api/questionnaire/model/QuestionnaireDetailReq'

const CLIENT = CORE.grpcCLIENT(Client)

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 单项 —————————————————————————————— //

  async getOne(one, TIP = '查询详情') {
    let obj = { ...one }

    // 未查询过根问卷
    if (!one.root.id) {
      const DTO = CORE.grpcDTO(OneClass, { questionnaireId: one.id })

      // 明确知道是循环问卷
      if (one.questionnaireType === 3) obj.root = { ...one }
      // 非循环问卷，或是问卷类型未知
      else {
        // 查询详情，更新问卷及类型
        const { dto = one } = await CORE.grpc(TIP, CLIENT, 'questionnaireDetail', DTO)
        obj = { ...dto, root: dto, periodId: dto.id }
      }

      // 非循环问卷，直接返回
      if (obj.questionnaireType !== 3) return obj

      // 循环问卷，查询所有期数
      const { dtos = [] } = await CORE.grpc(`${TIP}期数`, CLIENT, 'questionnaireStatisticsDateList', DTO)
      obj.periodList = dtos.map((x) => ({ id: x.questionnaireId, time: x.date, title: x.questionnaireName }))
      obj.periodId = (obj.periodList[0] || one).id

      // 期数为空，直接返回
      if (CORE.isEmpty(obj.periodList)) return obj
    }

    // 循环问卷，查询最近一期子问卷
    const DTO = CORE.grpcDTO(OneClass, { questionnaireId: obj.periodId })
    const resp = await CORE.grpc(TIP, CLIENT, 'questionnaireDetail', DTO)
    return { ...obj, ...resp.dto, id: obj.id }
  },
}
